import { shallowRef, type WatchOptions } from 'vue'
import { type Ref, watch } from 'vue'

/**
 * @file
 * @description
 * @author 黄敏
 * @since 2025-10-09 14:27
 */
export class CreateState<Default = unknown> {
  /** 内部可写的响应式状态对象 */
  private readonly _state: Ref<Default>
  private isDestroyed = false

  /** 状态是否已销毁时的统一告警 */
  private warnIfDestroyed(action: string): boolean {
    if (this.isDestroyed) {
      console.error(`[CreateState] 状态 "${this.name}" 已销毁，禁止执行：${action}`)
      return true
    }
    return false
  }

  /** 外部只读的响应式状态对象，支持Vue的响应式系统 */
  get state() {
    // 读取也提示（但仍返回最后一次值，以避免调用方崩溃）
    this.warnIfDestroyed('读取')
    return this._state.value
  }
  offs: (() => void)[] = []

  constructor(
    private readonly name: string,
    defaults: Default
  ) {
    this._state = shallowRef(_globalState_.runtime.get<Default>(this.name) ?? defaults)

    // 监听主进程状态变化，自动同步到当前 store
    const unwatch = _globalState_.runtime.onStateUpdated(this.name, data => {
      if (this.isDestroyed) return
      console.log('运行时状态已更新:', this.name, data)

      this._state.value = data.newValue as Default
    })
    this.offs.push(unwatch)
  }

  /**
   * 监听指定键的状态变化
   * @param callback - 状态变化回调函数
   * @param options - watch 选项
   * @returns Vue的watch停止函数
   */
  watch(callback: (newVal: Default, oldVal?: Default) => void, options?: WatchOptions) {
    if (this.warnIfDestroyed('watch 监听')) {
      return () => {}
    }
    const off = watch(this._state, (newVal, oldVal) => callback(newVal, oldVal), options)
    this.offs.push(off)
    return off
  }

  /**
   * 设置状态值
   * @param data - Default
   */
  set(data: Default) {
    if (this.warnIfDestroyed('设置')) return
    _globalState_.runtime.set(this.name, data)
  }

  destroy() {
    if (this.isDestroyed) {
      console.error(`[CreateState] 状态 "${this.name}" 已经销毁，请勿重复销毁。`)
      return
    }
    this.offs.forEach(off => off())
    this.offs = []
    _globalState_.runtime.clear(this.name)
    this.isDestroyed = true
  }
}
